package com.xiaochi.gateway.filter;

import cn.dev33.satoken.reactor.context.SaReactorSyncHolder;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import lombok.SneakyThrows;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 登录过滤器
 * @author zqx
 * @since 2024/9/4
 */
@Component
public class LoginFilter implements GlobalFilter {

    @Override
    @SneakyThrows
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //每次请求都set一下上下文 todo 兄弟们，这个项目你们测试多次后没有发现bug么 我现在两个浏览器分别登录两个账号，几十次请求中一定有几次tokenvalue会变成另一个账号的，然后一会又好了，一会又出现了
        // 解决这个问题
        SaReactorSyncHolder.setContext(exchange);
        //还可以 做什么黑白名单等等
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();
        //可以拿请求路径
        String path = request.getURI().getPath();
        if (path.equals("/auth/user/doLogin")){
            chain.filter(exchange);
        }
        //可以拿token
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        String loginId = (String) tokenInfo.getLoginId();
        if (StringUtils.isEmpty(loginId)){
            throw new Exception("未获取到用户信息");
        }
        mutate.header("loginId",loginId);
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }
}













